<?php

namespace App\bootstrap;

use Illuminate\Support\Str;
use support\Db;

use Webman\Bootstrap;

class ListenSql implements Bootstrap
{
    //执行的sql语句
    static $sql_debug = [];

    public static function start($worker)
    {
        if (getenv("APP_ENV") !== 'production') {
            Db::listen(function ($query) use ($worker) {
                $request = request();
                if ($request) {
                    $_key = $request->uri() . $request->getRealIp() . md5(serialize($request->all()));
                }

                $sql = $query->sql;
                $bindings = [];
                if ($query->bindings) {
                    foreach ($query->bindings as $v) {
                        if (is_numeric($v)) {
                            $bindings[] = $v;
                        } else {
                            $bindings[] = '"' . strval($v) . '"';
                        }
                    }
                }
                // $time = $query->time/100000;
                $execute = Str::replaceArray('?', $bindings, $sql);

                if (isset($_key)) {
                    self::$sql_debug[$_key][] = $execute;
                }

                //命令行模式
                if (!$worker) {
                    self::$sql_debug['console'][] = $execute;
                }
            });
        }
    }

}
